
void fs(int wid, int hei, float viswid, float vishei, float visx, float visy, int maxi, float maxm);

class FormFractalSingle : public Form
{
  public:
  
  void init(){

    Form::init("Fractal Single");
    id = 123;
    width = 600;
    height = 500;
    pos_x = 50;
    pos_y = 20;
    //b->text="timer";
    color = getRGB565(0x0000000);
    regClose(FormFractalSingle::close);
    regDraw(FormFractalSingle::draw);
  }

  static void close(Form* window){
    ::windows->removeWindow((Window*)formFractalSingle);
    ::windows->refresh();
    formFractalSingle=0;
  }

  static void draw(Form* self){
    fs(256, 192 , 2.8, 1.6, -1.1, -1.6, 255, 4);

  }


};



void fs(int wid, int hei, float viswid, float vishei, float visx, float visy, int maxi, float maxm){
  short* buffAddr = (short*)(((windows->screenBase+formFractalSingle->abs_pos_y+4+16)<<11)+((formFractalSingle->abs_pos_x+4)<<1));

	int i;
	int j;
	int index = 0;
	int clr;
	float ReaC;
	float ImaC;
	float dReaC;
	float dImaC;
	float ReaZ;
	float ImaZ;
	float ReaZ2;
	float ImaZ2;
	//int n;

	//n = 256 / maxi;

  // Zn+1 = (Zn)^2 + C;

	dReaC = (viswid) / ((float)wid - 1);
	dImaC = (vishei) / ((float)hei - 1);

	for (j = 0; j < hei; j++)
	{
    short* addr;
		for (i = 0; i < wid; i++)
		{
      addr = &(buffAddr[i+(j<<10)]);
      *addr = getRGB565(0x000000FF);//at 2Mbyte
		}
    flushDataCache();
	}
  //int t0 = IORD(MYTIMER, MYTIMER_32);
	ReaC = visy;
	for (j = 0; j < hei; j++)
	{
		ReaC += dReaC;
		ImaC = visx;
    IOWR(DEBUGGER, 2, 1);
		for (i = 0; i < wid; i++)
		{
			ImaC += dImaC;
			ReaZ = 0;
			ImaZ = 0;
			ReaZ2 = 0;
			ImaZ2 = 0;
			clr = 1;

			while (clr++ < maxi && ReaZ2 + ImaZ2 < maxm)
			{
				ReaZ2 = ReaZ * ReaZ;
				ImaZ2 = ImaZ * ImaZ;
				ImaZ = 2 * ImaZ * ReaZ + ImaC;
				ReaZ = ReaZ2 - ImaZ2 + ReaC;
			}
      short* addr0 = &(buffAddr[((i<<1)+0)+(((j<<1)+0)<<10)]);
      short* addr1 = &(buffAddr[((i<<1)+1)+(((j<<1)+0)<<10)]);
      short* addr2 = &(buffAddr[((i<<1)+0)+(((j<<1)+1)<<10)]);
      short* addr3 = &(buffAddr[((i<<1)+1)+(((j<<1)+1)<<10)]);
    
      int v1 = 0;
      int v2 = clr;
      //__asm__ __volatile__("setrgb %0,%1,%2,1":"=r"(v1):"r"(v1),"r"(v2));
      v1 = (v2 >> 2) << 5;
      *addr0 = v1;
      *addr1 = v1;
      *addr2 = v1;
      *addr3 = v1;
      
		}

    flushDataCache();
    //int t1 = IORD(MYTIMER, MYTIMER_32);
    //printf("%d,%d\r\n", j, t1-t0);
    //t0 = IORD(MYTIMER, MYTIMER_32);
	}
}
